//
//  ChatViewController.m
//  Conference
//
//  Created by chenxin on 12-11-15.
//
//

#import "ChatViewController.h"
#import "Constant.h"
#import "WebData.h"
#import "Globals.h"
#import "NetContant.h"
#import "ChatMsgEntity.h"
#import "UIBubbleTableViewCell.h"
#import "Globals.h"
#import "DateTool.h"
#import "Member.h"
#import "AppDelegate.h"
@interface ChatViewController ()

@end

@implementation ChatViewController
@synthesize txt_chat;
@synthesize bottomView;
@synthesize arrayOfData;
@synthesize currRecord;
@synthesize bubleTable;
@synthesize refreshHeaderView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.currRecord=0;
    }
    return self;
}

- (void)viewDidLoad
{ 
    [super viewDidLoad];
    self.bubleTable.separatorStyle=UITableViewCellSeparatorStyleNone;
    if (self.refreshHeaderView == nil) {
		
		self.refreshHeaderView = [[[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.bubleTable.bounds.size.height, self.view.frame.size.width, self.bubleTable.bounds.size.height)] autorelease];
		self.refreshHeaderView.delegate = self;
		[self.bubleTable addSubview:self.refreshHeaderView];
	}
    [self registerForKeyboardNotifications];
    [self initData];
    
}

-(void)initData{
    
    self.arrayOfData=[NSMutableArray arrayWithCapacity:0];
    
    NSThread *thread=[[[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil] autorelease];
    [thread start];
    
}

-(void)run{
    
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    
    NSString *sRet=[[WebData getInstance]getCustomerInfo:self.currRecord];
    
    [self performSelectorOnMainThread:@selector(onPostExecute:) withObject:sRet waitUntilDone:YES];
    
	[pool release];
    
}

-(void)onPostExecute:(NSString *)sRet{
    
    if ([sRet isEqualToString:[[NetContant getInstance] NET_CONNECT_FALSE]]) {
        
        
        [[Globals getInstance] showAlertView:[[Constant getInstance] data_isempty]];
        
        
    }else if([sRet isEqualToString:[[NetContant getInstance] NETWORK_RECORD_ISEMPTY]]){
        
//        [[Globals getInstance] showAlertView:[[Constant getInstance] data_isempty]];
        
    }else {
        @try {
            [self doNetRet:sRet];
            [self doNetInfo];
        }
        @catch (NSException *exception) {
            //[[Globals getInstance] showAlertView:[[Constant getInstance] net_exception]];
        }
        
    }
    
    [self doneLoadingTableViewData:@""];
    
}

-(void)doNetRet:(NSString *)sRet{
    
    NSArray *tables=[sRet componentsSeparatedByString:[[NetContant getInstance]TABLES_SPLIT_FLAG]];
    int iRecodeId = -1;
	int iLastRecode = -1;
    
    for (int i=0; i<[tables count]; i++) {
        if(nil!=[tables objectAtIndex:i]){
            NSArray *record=[[tables objectAtIndex:i] componentsSeparatedByString:[[NetContant getInstance] RECORDS_SPLIT_FLAG]];
            if([record count]>=6){
                
                @try {
                    iRecodeId=[[record objectAtIndex:0]intValue];
                    if(iLastRecode==-1)
                        iLastRecode=iRecodeId;
                    else if(iLastRecode>iRecodeId&&iRecodeId!=-1)
                        iLastRecode=iRecodeId;
                    self.currRecord=iLastRecode;
                    
                }
                @catch (NSException *exception) {
                    
                }
                
                ChatMsgEntity *chatMsgEntity=[[ChatMsgEntity alloc]init];
                chatMsgEntity.text=[record objectAtIndex:2];
                chatMsgEntity.date=[record objectAtIndex:5];
                chatMsgEntity.isComMeg=YES;
                chatMsgEntity.name=[record objectAtIndex:1];
                
                if(![self.arrayOfData containsObject:chatMsgEntity])
                    [self.arrayOfData addObject:chatMsgEntity];
                [chatMsgEntity release];
                
                if(![@"" isEqualToString:[record objectAtIndex:3]] && nil !=[record objectAtIndex:3]){
                    chatMsgEntity=[[ChatMsgEntity alloc]init];
                    chatMsgEntity.text=[record objectAtIndex:3];
                    chatMsgEntity.date=[record objectAtIndex:4];
                    chatMsgEntity.isComMeg=NO;
                    chatMsgEntity.name=@"客服";
                    if(![self.arrayOfData containsObject:chatMsgEntity])
                        [self.arrayOfData addObject:chatMsgEntity];
                    [chatMsgEntity release];
                }
                
            }
        }
    }
    
}

-(void)doNetInfo{
    
    [self.bubleTable reloadData];
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

//- (IBAction)textFieldDoneEditing:(id)sender {
//        //[sender resignFirstResponder];
//    
//}

- (IBAction)sendMsg:(id)sender {
    
    
    if ([txt_chat.text isEqualToString:@""]) {
        
        [[Globals getInstance] showAlertView:[[Constant getInstance] chat_isempty]];
        return;
    }
    
    NSThread *thread=[[[NSThread alloc] initWithTarget:self selector:@selector(PutDataThead) object:nil] autorelease];
    
    [thread start];

    
}

-(void)PutDataThead{


    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    
    NSString *sRet=[[WebData getInstance] putCustomerInfo:txt_chat.text];
    
    [self performSelectorOnMainThread:@selector(onPutDataPostExecute:) withObject:sRet waitUntilDone:YES];
    
	[pool release];


}

-(void)onPutDataPostExecute:(NSString *)sRet{
    
    if ([sRet isEqualToString:[[NetContant getInstance] NET_CONNECT_FALSE]]) {
        
        
        [[Globals getInstance] showAlertView:[[Constant getInstance] put_info_error]];
        
        
    }else if([sRet isEqualToString:[[NetContant getInstance] NETWORK_RECORD_ISEMPTY]]){
        
        [[Globals getInstance] showAlertView:[[Constant getInstance] put_info_error]];
        
    }else {
        @try {
            [self doPutDataNetRet:sRet];
            
            [self doPutDataNetInfo];
        }
        @catch (NSException *exception) {
            
        }
        
    }

}


-(void)doPutDataNetRet:(NSString *)sRet{

    ChatMsgEntity *chatMsgEntity =[[ChatMsgEntity alloc] init];
    chatMsgEntity.text=txt_chat.text;
    chatMsgEntity.date=[NSString stringWithFormat:@"%@ %@",[[DateTool getInstance] getNowDate],[[DateTool getInstance] getNowTime]];
    chatMsgEntity.isComMeg=YES;
     Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
    chatMsgEntity.name=member.userName;
    [self.arrayOfData addObject:chatMsgEntity];
    [chatMsgEntity release];
}

-(void)doPutDataNetInfo{

     txt_chat.text=@"";
    [self.bubleTable reloadData];
    
 //   NSIndexPath *indexPath=[NSIndexPath indexPathForRow:self.arrayOfData.count inSection:0];
 //   [self.bubleTable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewRowAnimationBottom animated:YES];


}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.txt_chat resignFirstResponder];
    return YES;
}

//注册键盘事件通知
-(void)registerForKeyboardNotifications{
    
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
#ifdef _IPHONE_5_0// 键盘高度变化通知，ios5.0新增的
	float version=[[[UIDevice currentDevice] systemVersion] floatValue];
	if (version>=5.0) {
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardwillChangeFrameNotification object:nil];
	}
#endif
}

//然后添加键盘事件的处理代码：
//获取到当前keyboard的高度以及动画时间，然后对视图进行对应的操作即可。
#pragma mark -
#pragma mark Responding to keyboard events
-(void)keyboardWillShow:(NSNotification *)notification{
	/*
     Reduce the size of the text view so that it's not obscured by the keyboard.
     Animate the resize so that it's in sync with the appearance of the keyboard.
     */
	NSDictionary *userInfo=[notification userInfo];
	// Get the origin of the keyboard when it's displayed.
	NSValue *aValue=[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
	// Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system.
	//The bottom of the text view's frame should align with the top of the keyboard's final position.
	CGRect keyboardRect=[aValue CGRectValue];
	//NSLog(@"%f",keyboardRect.size.height);
	//Get the duration of the animation
	NSValue *animationDurationValue=[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
	NSTimeInterval animationDuration;
	[animationDurationValue getValue:&animationDuration];
	//Animate the resize of the text view's frame in sync with the keyboard's appearance
	[self autoMovekeyBoard:keyboardRect.size.height duration:animationDuration];
    
}


-(void) autoMovekeyBoard: (float) h duration:(NSTimeInterval)animationDuration{
    
    
    [UIView beginAnimations:@"ResizeForKeyboard" context:self];
	[UIView setAnimationDuration:animationDuration];
    
	self.bottomView.frame = CGRectMake(0.0f, (float)(480.0-20.0-50.0-h), 320.0f, 50.0f);
    
    self.bubleTable.frame = CGRectMake(0.0f, 70.0f, 320.0f,480.0-20.0-70.0-50.0-h);
    
	[UIView commitAnimations];
    
}


-(void)keyboardWillHidden:(NSNotification *)notification{
	NSDictionary *userInfo=[notification userInfo];
	//     Restore the size of the text view (fill self's view).
	// Animate the resize so that it's in sync with the disappearance of the keyboard.
	NSValue *animationDurationValue=[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
	NSTimeInterval animationDuration;
	[animationDurationValue getValue:&animationDuration];
    [self autoMovekeyBoard:0 duration:animationDuration];
}


#pragma mark - UITableViewDelegate implementation

#pragma mark - UITableViewDataSource implementation

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	
    return [self.arrayOfData count];
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	
    ChatMsgEntity  *entity =[self.arrayOfData objectAtIndex:indexPath.row];
    
    
    CGSize size=[entity.text sizeWithFont:[UIFont systemFontOfSize:[UIFont systemFontSize]] constrainedToSize:CGSizeMake(220, 9999) lineBreakMode:UILineBreakModeWordWrap];
    
    float height = size.height+20;
    
    return height>100?height:100;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"tblBubbleCell";
    
    
    ChatMsgEntity  *entity =[self.arrayOfData objectAtIndex:indexPath.row];
    
    UIBubbleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if(cell ==nil){
		NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"UIBubbleTableViewCell" owner:self options:nil];
		for (id oneObject in array) {
			if ([oneObject isKindOfClass:[UIBubbleTableViewCell class]]) {
				cell=oneObject;
				break;
			}
		}
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    
    CGSize size=[entity.text sizeWithFont:[UIFont systemFontOfSize:[UIFont systemFontSize]] constrainedToSize:CGSizeMake(190, 9999) lineBreakMode:UILineBreakModeWordWrap];
    
    float x = entity.isComMeg?90:cell.frame.size.width-90-size.width;
    float y =5.0;
    
    cell.label_content.font=[UIFont systemFontOfSize:[UIFont systemFontSize]];
    cell.label_content.frame=CGRectMake(x, y, size.width, size.height);
    cell.label_content.text=entity.text;
    cell.label_name.text=entity.name;
    
    
    if (entity.isComMeg) {
        
        cell.image_content_bg.image= [[UIImage imageNamed:@"bubbleMine.png"] stretchableImageWithLeftCapWidth:21 topCapHeight:14];
        cell.image_content_bg.frame=CGRectMake(x-18, y-4 , size.width+30, size.height+15);
        
        cell.image_head.frame=CGRectMake(10, 0, 55, 55);
        cell.label_name.frame=CGRectMake(10, 55, 60, 25);
        
        
    }else {
        
        cell.image_content_bg.image= [[UIImage imageNamed:@"bubbleSomeone.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:14];
        cell.image_content_bg.frame=CGRectMake(x-9, y-4 , size.width+26, size.height+15);
        
        cell.image_head.frame=CGRectMake(cell.frame.size.width-55-10, 0, 55, 55);
        cell.label_name.frame=CGRectMake(cell.frame.size.width-55-10, 55, 60, 25);
    }
    
    return cell;
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData:(NSString *)errInfo{
	
	//  model should call this when its done loading
	_reloading = NO;
    
    //    if([errInfo isEqualToString:@""]){
    //        self.listSite=[self loadSiteListViewData];
    //        [self.tableView reloadData];
    //        
    //    }else {
    //        [[Globals shared] showAlert:@"错误" message:errInfo];
    //    }
    //    
    [self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.bubleTable];
  	
}


#pragma mark -
#pragma mark UIScrollViewDelegate Methods



- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	
	[self.refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[self.refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
    
	NSThread *thread=[[[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil] autorelease];
    [thread start];
}




- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}



- (void)dealloc {
    [arrayOfData release];
    [txt_chat release];
    [bottomView release];
    [bubleTable release];
    [refreshHeaderView release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setArrayOfData:nil];
    [self setTxt_chat:nil];
    [self setBottomView:nil];
    [self setBubleTable:nil];
    [self setRefreshHeaderView:nil];
    [super viewDidUnload];
}

@end
